//
//  ActivityMemberViewController.m
//  WindRunner
//
//  Created by leeqb on 12/26/14.
//  Copyright (c) 2014 poweropt. All rights reserved.
//

#import "ActivityMemberViewController.h"

@interface ActivityMemberViewController ()
{
    NSMutableArray *_activityMembers;
}
@end

@implementation ActivityMemberViewController

- (id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if(self) {
        _activityMembers = [[NSMutableArray alloc] init];
    }
    return self;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationItem.title = LocalStringEvent(@"NAV_TITLE_ACTIVITY_MEMBER");
    [self refreshData];
}

- (void)refreshData
{
    NSDictionary *requestData = @{@"id":self.data[@"id"]};
    FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                             interface:@"activejoinlist"
                                                                params:requestData];
    [FMNetwork request:requestObj showMask:YES success:^(NSDictionary *data) {
        NSArray *record = data[@"record"];
        if(![record isEqual:[NSNull null]]) {
            [_activityMembers addObjectsFromArray:record];
            [_memberTable reloadData];
        }
    } falied:^(NSError *error) {
    }];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _activityMembers.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ActivityMemberCell" forIndexPath:indexPath];
    UIImageView *iconView = (UIImageView *)[cell viewWithTag:1];
    UILabel *nameLabel = (UILabel *)[cell viewWithTag:2];
    UIView *genderAgeView = (UIView *)[cell viewWithTag:3];
    UILabel *ageLabel = (UILabel *)[genderAgeView viewWithTag:31];
    UIImageView *genderImageView = (UIImageView *)[genderAgeView viewWithTag:32];
    UILabel *distanceLabel = (UILabel *)[cell viewWithTag:4];
    UIButton *joinDenyButton = (UIButton *)[cell viewWithTag:5];
    UIButton *joinAcceptButton = (UIButton *)[cell viewWithTag:6];
    
    [iconView showInCircle];
    genderAgeView.layer.cornerRadius = 8;
    genderAgeView.layer.masksToBounds = YES;
    joinDenyButton.accessibilityValue = [NSString stringWithFormat:@"%@", @(indexPath.row)];
    joinAcceptButton.accessibilityValue = [NSString stringWithFormat:@"%@", @(indexPath.row)];
    
    NSDictionary *rowData = _activityMembers[indexPath.row];
    if(rowData) {
        nameLabel.text = [NSString formatString:rowData[@"nickname"]];
        
        LEDownloadManager *downloadManager = [[LEDownloadManager alloc] initWithTarget:iconView];
        [downloadManager downLoadImageWithURL:rowData[@"headicon"] imagetype:@"ContactHeadIocns"];
        
        NSString *locationStringX = [NSString formatString:rowData[@"lastlocationX"]];
        NSString *locationStringY = [NSString formatString:rowData[@"lastlocationY"]];
        if(![locationStringX isEqualToString:@""] && ![locationStringY isEqualToString:@""]) {
            double locationX = [locationStringX doubleValue];
            double locationY = [locationStringX doubleValue];
            double distanceMeters = [FMCommonFun distanceBetweenOrderBy:CURR_COORDINATE_X
                                                                       :locationX
                                                                       :CURR_COORDINATE_Y
                                                                       :locationY];
            distanceLabel.text = [NSString stringWithFormat:@"%.1f", distanceMeters];
        } else {
            distanceLabel.text = @"0";
        }
        
        // 年龄
        NSString *strBirthTimestamp = [NSString formatString:rowData[@"birthday"]];
        long long birthTimestamp = 0;
        if(![strBirthTimestamp isEqualToString:@""]) {
            birthTimestamp = [rowData[@"birthday"] longLongValue];
            ageLabel.text = [NSString stringWithFormat:@"%@", @([FMCommonFun getYearIntervalFromTimestamp:birthTimestamp])];
        } else {
            ageLabel.text = @"0";
        }
        
        // 性别
        if([[NSString formatString:rowData[@"sex"]] integerValue] == 0) { // 女
            genderImageView.image = [UIImage imageNamed:@"ic_female.png"];
        } else { // 男
            genderImageView.image = [UIImage imageNamed:@"ic_male.png"];
        }
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];
}

- (IBAction)activityJoinAccept:(UIButton *)sender {
    NSInteger row = [sender.accessibilityValue integerValue];
    NSDictionary *rowData = _activityMembers[row];
    
    NSDictionary *requestData = @{@"id":self.data[@"id"],
                                  @"userid":rowData[@"id"]};
    FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                             interface:@"activejoinaccept"
                                                                params:requestData];
    [FMNetwork request:requestObj showMask:YES success:^(NSDictionary *data) {
        [_activityMembers removeObjectAtIndex:row];
        [_memberTable reloadData];
    } falied:^(NSError *error) {
        NSString *errorCode = [NSString formatString:error.userInfo[@"errorCode"]];
        if([errorCode isEqualToString:@"000006"]) {
            [FMToast showMessage:@"未知错误"];
        } else if([errorCode isEqualToString:@"000007"]) {
            [FMToast showMessage:@"超过最大人数"];
        } else {
            [FMToast showMessage:@"申请失败"];
        }
    }];
}

- (IBAction)activityJoinDeny:(UIButton *)sender {
    NSInteger row = [sender.accessibilityValue integerValue];
    NSDictionary *rowData = _activityMembers[row];
    
    NSDictionary *requestData = @{@"id":self.data[@"id"],
                                  @"userid":rowData[@"id"]};
    FMRequestObject *requestObj = [[FMRequestObject alloc] initWithRUL:BASE_API_URL_WINDRUNNER
                                                             interface:@"activejoindeny"
                                                                params:requestData];
    [FMNetwork request:requestObj showMask:YES success:^(NSDictionary *data) {
        [_activityMembers removeObjectAtIndex:row];
        [_memberTable reloadData];
    } falied:^(NSError *error) {
        NSString *errorCode = [NSString formatString:error.userInfo[@"errorCode"]];
        if([errorCode isEqualToString:@"000006"]) {
            [FMToast showMessage:@"未知错误"];
        } else {
            [FMToast showMessage:@"申请失败"];
        }
    }];
}

@end
